package com.lkxicy.wos.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lkxicy.wos.pojo.entity.Staff;
import com.lkxicy.wos.service.StaffService;
import com.lkxicy.wos.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@RestController
@RequestMapping("/wos/v1/login/")
public class LoginController {

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private StaffService staffService;

    @PostMapping("login")
    public Response login(@RequestParam("staffNumber") String staffNumber,
                          @RequestParam("password") String password){
        String[] maps = staffService.staffLogin(staffNumber, password);
        return Response.setCodeMsgData(Integer.parseInt(maps[0]),maps[1],maps[2]);
    }

    @PostMapping("getTokenInfo")
    public Response getTokenInfo(@RequestParam("token") String token){
        try{
            Jedis jedis = jedisPool.getResource();
            String jsonRst = jedis.get(token);
            ObjectMapper mapper = new ObjectMapper();
            Staff info = mapper.readValue(jsonRst, Staff.class);
            jedis.close();
            return Response.success(info);
        }catch(JsonProcessingException e ){
            throw new RuntimeException("redis 数据解析异常");
        }

    }

    @PostMapping("logout")
    public Response logout(@RequestParam("token") String token){
        Jedis jedis = jedisPool.getResource();
        jedis.del(token);
        jedis.close();
        return Response.success("退出登录成功！");
    }



}
